package demo07

/**
 * @author xiaoZhao
 * @date 2022/7/25
 * @describe 模式匹配不同的用法
 */
object Test02_MathType {
  def main(args: Array[String]): Unit = {
    // 1，匹配常量
    def describeConst(s: Any): String = s match {
      case 1 => "number 1"
      case "hello" => "String hello"
      case '+' => "+"
      case 's' => "Char s"
      case _ => ""
    }

    println(describeConst(1))
    println(describeConst('s'))
    println(describeConst(11))

    // 2.匹配类型 list集合存在泛型擦除
    def deprecateType(x: Any): String = x match {
      case i: Int => "int" + i
      case s: String => "String" + s
      case list: List[String] => "list" + list
      case array: Array[Int] => "Array[Int]" + array.mkString("-")
      case a => "Something type"
    }

    println(deprecateType(23))
    println(deprecateType("12"))
    println(deprecateType(List("mi", "hao")))
    println(deprecateType(List(12, 21)))
    println(deprecateType(Array("ni")))
    println(deprecateType(Array(12, 21, 43)))

    // 3.匹配数组
    for (arr <- List(
      Array(0),
      Array(1, 0),
      Array(0, 1, 0),
      Array(1, 1, 0),
      Array(12, 21, 34, 32),
      Array("hello", 34, 32),
    )) {
      val result = arr match {
        case Array(0) => "0"
        case Array(1, 0) => "Array(1,0)"
        case Array(x, y) => "Array:" + x + ", " + y
        case Array(0, _*) => "以0开头的数组"
        case Array(x, 1, y) => "中间为1 的三元数组"
        case _ => "something else"
      }
    }


    // 4.匹配列表 方式一
    for (list <- List(
      List(0),
      List(1, 0),
      List(0, 0, 0),
      List(1, 1, 0),
      List(999)
    )) {
      val result = list match {
        case List(0) => "0"
        case List(x, y) => "list:" + x + ", " + y
        case List(0, _*) => "以0开头的list"
        case List(a) => "list(a)" + a
        case _ => "something else"
      }
    }

    // 方式二
    val list = List(1, 34, 3, 2, 3, 2, 3, 6)
    list match {
      case first :: second :: rest => println(s"first:$first second: $second rest: $rest")
      case _ => "something else"
    }

    // 5.元组类型
    for (tuple <- List(
      (0, 1),
      (0, 1),
      (0, 1, 0),
      (0, 1, 1),
      ("hello", true, 0.5)
    )) {
      val result = tuple match {
        case (a,b) => " "+ a + ", " +b
        case (0,_) => "(0,_)"
        case (a,1,_) => "(a,1,_)" + a
        case (x,y,z) => "(x,y,z)"
        case _ => "something else"
      }
    }
  }
}
